import 'package:flutter/material.dart';
import 'package:gold/app/user_provider.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/model/address_model.dart';
import 'package:gold/model/gold_recover_shop_model.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/cache_data.dart';
import 'package:gold/utils/xfg_utils.dart';
import 'package:popover/popover.dart';
import 'package:provider/provider.dart';
import 'package:gold/ui/home/recover/gold_recover_viewmodel.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';

/// @description: 黄金投资
/// @author tangzhentao
/// @created at 19:22 2024/11/30


class GoldRecoverPage extends StatelessWidget {
  /// 金价
  final double price;

  const GoldRecoverPage({super.key, required this.price});

  @override
  Widget build(BuildContext context) {
    return ProviderWidget<GoldRecoverViewmodel>(
      model: GoldRecoverViewmodel(price),
      builder: (ctx, recover) => Scaffold(
        resizeToAvoidBottomInset: true,
        appBar: xfgAppbar(title: '黄金回收'),
        body: SingleChildScrollView(
          padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, XfgSize().bottomBarHeight),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: XfgSize().size107,
                decoration: const BoxDecoration(image: DecorationImage(image: AssetImage(Res.imagesGoldRecoverTopBg), fit: BoxFit.cover)),
                alignment: Alignment.center,
                child: XfgText('实时金价（元/克）\n', fontSize: XfgSize().text14, color: XfgColor.white, textAlign: TextAlign.center, height: 1.5, children: [
                  TextSpan(text: ctx.select<UserProvider, GoldQuotes?>((k) => k.goldQuotes)?.map[realTimeGoldPrice]?.lastPrice?? '0.00', style: TextStyle(fontSize: XfgSize().text40, fontWeight: FontWeight.bold))
                ]),
              ),
              Container(
                margin: EdgeInsets.only(top: XfgSize().size8, bottom: XfgSize().size20),
                decoration: BoxDecoration(color: XfgColor.goldRecoverTips, borderRadius: BorderRadius.circular(XfgSize().size4)),
                height: XfgSize().size32,
                alignment: Alignment.center,
                child: XfgText('提示：显示以每天零时零分更新时间为实时时间', fontSize: XfgSize().text14, color: XfgColor.red),
              ),
              XfgText('回收方式', fontSize: XfgSize().text20, color: XfgColor.text1D, bold: FontWeight.bold),
              Container(
                margin: EdgeInsets.only(top: XfgSize().size12, bottom: XfgSize().size18),
                child: Builder(builder: (ctx) {
                  final method = ctx.select<GoldRecoverViewmodel, String>((k) => k.method);
                  return Row(
                    children: [
                      _recoverWidget('线上回收', '快递上门 省时省心', Res.imagesGoldRecoverOnline, method == 'online', onTap: () => recover.method = 'online'),
                      SizedBox(width: XfgSize().size10),
                      _recoverWidget('门店回收', '现场交易 安全放心', Res.imagesGoldRecoverShop, method == 'offline', onTap: () => recover.method = 'offline'),
                    ],
                  );
                }),
              ),
              XfgText('订单信息', fontSize: XfgSize().text20, color: XfgColor.text1D, bold: FontWeight.bold),
              /// 订单信息
              Container(
                decoration: white6Decoration,
                margin: EdgeInsets.only(top: XfgSize().size12, bottom: XfgSize().size32),
                child: Column(
                  children: [
                    _orderInfoWidget('业务类型', child: LayoutBuilder(builder: (con, constraints) {
                      final type = con.select<GoldRecoverViewmodel, int>((k) => k.type);
                      return GestureDetector(
                        onTap: () async {
                          final result = await _showPickType(con, type, constraints.maxWidth);
                          if (result != null) recover.type = result;
                        },
                        child: Container(
                          height: XfgSize().size38,
                          padding: EdgeInsets.only(left: XfgSize().size20, right: XfgSize().size12),
                          decoration: BoxDecoration(border: Border.all(color: XfgColor.colorE, width: XfgSize().size0_5)),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              XfgText(type == 1 ? '定价后来料':'来料后定价', fontSize: XfgSize().text14, color: XfgColor.text1),
                              Icon(Icons.keyboard_arrow_down_rounded, size: XfgSize().size24, color: XfgColor.text3)
                            ],
                          ),
                        ),
                      );
                    })),
                    _orderInfoWidget('卖出克数', child: Container(
                      height: XfgSize().size38,
                      padding: EdgeInsets.only(left: XfgSize().size20, right: XfgSize().size12),
                      decoration: BoxDecoration(border: Border.all(color: XfgColor.colorE, width: XfgSize().size0_5)),
                      alignment: Alignment.centerLeft,
                      child: TextField(
                        controller: recover.weightController,
                        focusNode: recover.weightNode,
                        keyboardType: TextInputType.numberWithOptions(decimal: true),
                        onChanged: recover.onWeightChanged,
                        style: TextStyle(fontSize: XfgSize().text14, color: XfgColor.text1D),
                        decoration: InputDecoration(
                            border: InputBorder.none,
                            contentPadding: EdgeInsets.zero,
                            isCollapsed: true,
                            isDense: true,
                            hintText: '请输入克数',
                            hintStyle: TextStyle(fontSize: XfgSize().text14, color: XfgColor.text3)
                        ),
                      ),
                    )),
                    _orderInfoWidget('保证金额', child: SizedBox(
                      height: XfgSize().size38,
                      child: Builder(builder: (con) {
                        final weight = con.select<GoldRecoverViewmodel, double>((k) => k.weight);
                        return Row(
                          children: [
                            XfgText('¥', fontSize: XfgSize().text12, color: XfgColor.theme, children: [
                              TextSpan(text: (weight * price * CacheData().collateralRate).toStringAsFixed(2), style: TextStyle(fontSize: XfgSize().text18)),
                            ]),
                            SizedBox(width: XfgSize().size14),
                            XfgText('请确认余额充足', fontSize: XfgSize().text12, color: XfgColor.theme)
                          ],
                        );
                      }),
                    )),
                    Builder(builder: (con) {
                      final method = con.select<GoldRecoverViewmodel, String>((k) => k.method);
                      Widget child;
                      if (method == 'online') {
                        final address = con.select<GoldRecoverViewmodel, AddressModel?>((k) => k.address);
                        child = XfgText(address?.address?? '请选择取件地址', fontSize: XfgSize().text14, color: XfgColor.text3);
                      } else {
                        final shop = con.select<GoldRecoverViewmodel, GoldRecoverShopModel?>((k) => k.shop);
                        child = XfgText(shop?.name?? '请选择预约门店', fontSize: XfgSize().text14, color: XfgColor.text3);
                      }
                      return _orderInfoWidget(method == 'online' ? '取件地址':'预约门店', child: GestureDetector(
                        onTap: recover.location,
                        child: Container(
                          padding: EdgeInsets.fromLTRB(XfgSize().size20, XfgSize().size10, XfgSize().size12, XfgSize().size10),
                          decoration: const BoxDecoration(color: XfgColor.colorE),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(child: child),
                              Icon(Icons.chevron_right_outlined, size: XfgSize().size24, color: XfgColor.text3)
                            ],
                          ),
                        ),
                      ));
                    }),
                    Builder(builder: (con) {
                      final method = con.select<GoldRecoverViewmodel, String>((k) => k.method);
                      final dateTime = con.select<GoldRecoverViewmodel, String?>((k) => k.time);
                      Widget child;
                      if (method == 'online') {
                        child = XfgText(dateTime?? '请选择预约门店时间', fontSize: XfgSize().text14, color: XfgColor.text3);
                      } else {
                        child = XfgText(dateTime?? '请选择预约上门时间', fontSize: XfgSize().text14, color: XfgColor.text3);
                      }
                      return  _orderInfoWidget(method == 'online' ? '取件时间':'到店时间', child: GestureDetector(
                        onTap: recover.dateTime,
                        child: Container(
                          height: XfgSize().size38,
                          padding: EdgeInsets.fromLTRB(XfgSize().size20, XfgSize().size10, XfgSize().size12, XfgSize().size10),
                          decoration: const BoxDecoration(color: XfgColor.colorE),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(child: child),
                              Icon(Icons.chevron_right_outlined, size: XfgSize().size24, color: XfgColor.text3)
                            ],
                          ),
                        ),
                      ));
                    })
                  ],
                ),
              ),
              TextButton(
                onPressed: ctx.select<GoldRecoverViewmodel, bool>((k) => k.canClick) ? recover.confirmReserve:null,
                style: xfgButtonStyle(Size(XfgSize().size342, XfgSize().size50), radius: XfgSize().size50),
                child: XfgText('确认预约', fontSize: XfgSize().text18, color: XfgColor.white, bold: FontWeight.w500),
              )
            ],
          ),
        ),
      ),
    );
  }

  /// 回收方式
  Widget _recoverWidget(String text, String subText, String image, bool select, {GestureTapCallback? onTap}) => Expanded(
    child: Ink(
      height: XfgSize().size130,
      decoration: BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size6), border: select ? Border.all(color: XfgColor.theme, width: XfgSize().size0_5):null),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(XfgSize().size6),
        child: Stack(
          children: [
            Padding(
              padding: EdgeInsets.only(left: XfgSize().size18),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(image, width: XfgSize().size32, height: XfgSize().size32),
                  SizedBox(height: XfgSize().size14),
                  XfgText(text, fontSize: XfgSize().text18, color: XfgColor.text1D, bold: FontWeight.bold),
                  SizedBox(height: XfgSize().size6),
                  XfgText(subText, fontSize: XfgSize().text14, color: XfgColor.text3),
                ],
              ),
            ),
            Align(alignment: Alignment.topRight, child: Visibility(visible: select, child: Image.asset(Res.imagesGoldRecoverChecked, width: XfgSize().size34, height: XfgSize().size34)))
          ],
        ),
      ),
    ),
  );

  /// 订单信息Widget
  Widget _orderInfoWidget(String text, {required Widget child}) => Padding(
    padding: EdgeInsets.fromLTRB(XfgSize().size10, XfgSize().size10, XfgSize().size10, XfgSize().size16),
    child: Row(
      children: [
        SizedBox(width: XfgSize().size88, child: XfgText(text, fontSize: XfgSize().text18, color: XfgColor.text1D, bold: FontWeight.w500)),
        Expanded(child: child)
      ],
    ),
  );

  /// 业务类型
  Future<int?> _showPickType(BuildContext ctx, int type, double width) async {
    return await showPopover<int>(
        barrierColor: XfgColor.transparent,
        backgroundColor: XfgColor.white,
        radius: XfgSize().size10,
        transition: PopoverTransition.other,
        arrowDxOffset: XfgSize().size107,
        arrowDyOffset: -22,
        arrowWidth: 0,
        arrowHeight: 24,
        width: width,
        height: XfgSize().size80,
        context: ctx,
        bodyBuilder: (_) => Column(
          children: [
            _typeItemWidget('定价后来料', type == 1, onTap: () => XfgNav.pop(1)),
            _typeItemWidget('来料后定价', type == 2, onTap: () => XfgNav.pop(2)),
          ],
        )
    );
  }

  /// 性别通用布局
  Widget _typeItemWidget(String text, bool select, {GestureTapCallback? onTap}) => Expanded(
    child: Ink(
      color: select ? XfgColor.typeSelectedBg:XfgColor.background,
      padding: EdgeInsets.symmetric(horizontal: XfgSize().size22),
      child: InkWell(
        onTap: () {
          if (!select) {
            onTap?.call();
          }
        },
        child: Align(
          alignment: Alignment.centerLeft,
          child: XfgText(text, color: XfgColor.text1, fontSize: XfgSize().text16),
        ),
      ),
    ),
  );
}